import axios from 'axios'
import { getToken } from '@/utils/auth'
const service = axios.create({
  baseURL: process.env.VUE_APP_API, // url = base url + request url
  timeout: 5000                 // request timeout
  // withCredentials: true
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const _TOKEN = getToken()
    if (_TOKEN) {
      config.headers['Authorization'] = _TOKEN
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(response => {
  const res = response.data
  if (res.code !== 200) {
    if (res.code === -1) {
      window.location = '/#/user_info'
    }
  } else {
    return response
  }
}, error => {
  return Promise.reject(error)
})

export function postData (url, data) {
  return new Promise((resolve, reject) => {
    service.post(url, data)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}

export function getData (url, params) {
  return new Promise((resolve, reject) => {
    service.get(url, { params: params })
      .then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err.data)
      })
  })
}
